from typing import List, Dict
import qbittorrentapi
from .base import TorrentClient

class QBittorrentClient(TorrentClient):
    def __init__(self, host: str, port: int, username: str, password: str):
        self.host = host
        self.port = port
        self.username = username
        self.password = password
        self.client = qbittorrentapi.Client(
            host=f"{host}:{port}",
            username=username,
            password=password
        )
    
    async def connect(self) -> bool:
        try:
            self.client.auth_log_in()
            return True
        except Exception as e:
            print(f"连接qBittorrent失败: {str(e)}")
            return False
    
    async def get_torrents(self) -> List[Dict]:
        try:
            torrents = self.client.torrents_info()
            return [{
                "hash": torrent.hash,
                "name": torrent.name,
                "save_path": torrent.save_path,
                "content_path": getattr(torrent, 'content_path', ''),
                "state": torrent.state,
                "size": torrent.size,
                "progress": torrent.progress,
                "ratio": torrent.ratio,
                "seeding_time": getattr(torrent, 'seeding_time', 0),
                "files": self._get_torrent_files(torrent.hash)
            } for torrent in torrents]
        except Exception as e:
            print(f"获取种子信息失败: {str(e)}")
            return []
    
    def _get_torrent_files(self, torrent_hash: str) -> List[Dict]:
        try:
            files = self.client.torrents_files(torrent_hash=torrent_hash)
            return [{
                "name": file.name,
                "size": file.size,
                "progress": file.progress,
                "priority": file.priority,
                "is_seed": getattr(file, 'is_seed', False),
                "piece_range": getattr(file, 'piece_range', ''),
                "availability": getattr(file, 'availability', 0)
            } for file in files]
        except Exception as e:
            print(f"获取种子文件失败: {str(e)}")
            return []
    
    async def get_seeding_files(self) -> List[Dict]:
        try:
            torrents = self.client.torrents_info(filter="seeding")
            result = []
            for torrent in torrents:
                files = self._get_torrent_files(torrent.hash)
                for file in files:
                    result.append({
                        "torrent_name": torrent.name,
                        "file_name": file["name"],
                        "file_size": file["size"],
                        "path": f"{torrent.save_path}/{file['name']}",  # 修改这里，从file_path改为path
                        "file_path": f"{torrent.save_path}/{file['name']}",  # 保留这个键以兼容可能使用它的其他代码
                        "progress": file["progress"],
                        "priority": file["priority"],
                        "is_seed": file["is_seed"],
                        "piece_range": file["piece_range"],
                        "availability": file["availability"]
                    })
            return result
        except Exception as e:
            print(f"获取做种文件失败: {str(e)}")
            return []
    
    async def test_connection(self) -> bool:
        try:
            self.client.auth_log_in()
            version = self.client.app_version()
            return True
        except Exception as e:
            print(f"QBittorrent connection test failed: {e}")
            return False
